package com.xgk.boot.module.core.job;

import cn.hutool.core.date.StopWatch;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xgk.boot.module.core.dal.entity.truck.TruckOrderApiLogDO;
import com.xgk.boot.module.core.service.truck.TruckOrderApiLogServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;

@Slf4j
@Component
public class OrderApiLogClearJob {

    @Resource
    private TruckOrderApiLogServiceImpl truckOrderApiLogService;

    /**
     * 每天凌晨1点执行，删除2个月前的API调用日志
     * 使用cron表达式：秒 分 时 日 月 周
     */
    @Scheduled(cron = "0 0 1 * * ?")
    public void scheduleClearApiLog() {
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try {
            log.info("开始清理2个月前的API调用日志...");
            Instant twoMonthsAgo = Instant.now().minus(2, ChronoUnit.MONTHS);
            // 创建Wrapper来构建删除条件
            LambdaQueryWrapper<TruckOrderApiLogDO> wrapper = new LambdaQueryWrapper<>();
            wrapper.le(TruckOrderApiLogDO::getCreateTime, twoMonthsAgo);
            long count = truckOrderApiLogService.count(wrapper);
            // 执行删除并获取删除是否成功
            boolean success = truckOrderApiLogService.remove(wrapper);
            log.info("成功清理{}条2个月前的API调用日志,清理状态{}", count,success);
        } catch (Exception e) {
            log.error("清理API调用日志时发生异常", e);
        }finally {
            stopWatch.stop();
            double totalTimeSeconds = stopWatch.getTotalTimeSeconds();
            if(totalTimeSeconds>2){
                log.error("清理API调用日志cost:"+totalTimeSeconds);
            }
        }
    }
}
